package cn.wegoteam.shop.po;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;

import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

import cn.wegoteam.shop.cache.StaticDataCache;
import cn.wegoteam.shop.util.Const;
import cn.wegoteam.shop.util.GetReqRes;
import cn.wegoteam.shop.util.MyString;

/**
 * Ordermeta entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "cart", catalog = "shop")
public class Cart extends BasePo implements java.io.Serializable {

	/**
	 * 删除订单会级联删除对应的Cart
	 * 
	 */

	private Integer id;
	private Order order;
	private Product product;
	private String comment;
	private Integer score;//评分
	private Integer num;
	private String attrsString;//商品属性存储字符
	private int flag;//标志位
	private boolean anonymous;//匿名评论

	
	/**
	 * 根据所有购物车中的商品，返回存储到cookie中的字符串
	 * @param cs
	 * @return
	 */
	@Transient
	public static String getCookieString(Map<String,Cart> cs){
		StringBuilder sb = new StringBuilder();
		for(String key:cs.keySet())
		{
			Cart c = cs.get(key);
			sb.append("&"+String.format(Const.COOKIE_CART, c.getProduct().getId()+"",c.getNum(),c.getAttrsString()));
		}
		if(sb.length()>0)
			return sb.toString().replaceFirst("&", "");
		else
			return "";
	}

	/**
	 * 获取cookie中所有商品的id号
	 * @param numbs 商品id号对应的数量
	 * @return
	 */
	@Transient
	public static String getProductIds(){
		Map<String,Cart> cs = getCarts(false);
		StringBuilder ids = new StringBuilder("-1");
		for (String id : cs.keySet()) {
				ids.append(","+id);
		}
		return ids.toString();
	}
	
	/**
	 * 从cookie中返回List<cart>
	 * @param setAttr 是否加载静态数据
	 * @return
	 */
	@Transient
	public static Map<String,Cart> getCarts(boolean setAttr){
		//{5,9,SN1_1|SN1_2}&{5,9,SN1_1|SN1_2}
		String cookieString = MyString.isEmpty(GetReqRes.getCookie(Const.SESS_GOODS)) ? ""
				: GetReqRes.getCookie(Const.SESS_GOODS);
		Map<String,Cart> cs= new HashMap<String,Cart>();
		if(MyString.isEmpty(cookieString))
			return cs;
		
		String[] prods = cookieString.split("&");
		Cart c;
		Product p;
		for(String prod:prods){
			c = new Cart();
			p = new Product();
			prod = prod.replace("{", "").replace("}", "");
			String prodFields[] = prod.split(",");
			p.setId(Integer.parseInt(prodFields[0]));
			c.setProduct(p);
			c.setNum(Integer.parseInt(prodFields[1]));
			if(prodFields.length==3)
				c.setAttrsString(prodFields[2]);
			else
				c.setAttrsString("");
			cs.put(p.getId()+"", c);
		}
		return cs;
		
	}
	@Transient
	public static int getCartsNum(){
		String cookieString = MyString.isEmpty(GetReqRes.getCookie(Const.SESS_GOODS)) ? ""
				: GetReqRes.getCookie(Const.SESS_GOODS);
		if(MyString.isEmpty(cookieString))
			return 0;
		String[] prods = cookieString.split("&");
		return prods.length;
	}
	/**
	 * 根据商品返回购物车类,去除不可用的商品及剩余量为0商品
	 * @param products
	 * @param numbs
	 * @return
	 */
	@Transient
	public static Map<String,Cart> getCarts(List<Product> products){
		Map<String,Cart> cs = getCarts(true);
		for (Product p : products) {
			Cart c = cs.get(p.getId()+"");
			if(p.getFlag()>0&&p.getRemainder()>0){
				c.setProduct(p);
				if(c.getNum()>p.getRemainder())
					c.setNum(p.getRemainder());
			}
			else
				cs.remove(p.getId()+"");
		}
		return cs;
	}
	/**
	 * 返回所有属性对应的静态类，jsp 页面通过Cart.attrs即可获取
	 * @return
	 */
	@Transient
	public List<Staticdata> getAttrs() {
		List<Staticdata> attrs = new ArrayList<Staticdata>();
		if(MyString.isEmpty(attrsString))
			return attrs;
		for(String attr:attrsString.split("\\|")){
			Staticdata sd = StaticDataCache.getStaticdata(attr);
			if(MyString.isEmpty(sd.getCode()))
				continue;
			attrs.add(sd);
		}
		return attrs;
	}
	/**
	 * 返回所有属性对应的静态类名称，jsp 页面通过Cart.attrs即可获取
	 * @return
	 */
	@Transient
	public String getAttrsName() {
		StringBuilder sb = new StringBuilder();
		if(MyString.isEmpty(attrsString))
			return "";
		for(String attr:attrsString.split("\\|")){
			Staticdata sd = StaticDataCache.getStaticdata(attr);
			if(MyString.isEmpty(sd.getCode()))
				continue;
			sb.append("【"+sd.getName()+"】");
		}
		return sb.toString();
	}
	
	// Constructors


	// Property accessors
	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "oid", nullable = false)
	public Order getOrder() {
		return this.order;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "pid", nullable = false)
	public Product getProduct() {
		return this.product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	@Column(name = "comment", length = 200)
	public String getComment() {
		return this.comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	@Column(name = "attrsString", length = 200)
	public String getAttrsString() {
		return this.attrsString;
	}

	public void setAttrsString(String attrsString) {
		this.attrsString = attrsString;
	}
	@Column(name = "anonymous")
	@org.hibernate.annotations.Type(type="yes_no")
	public boolean isAnonymous() {
		return anonymous;
	}

	public void setAnonymous(boolean anonymous) {
		this.anonymous = anonymous;
	}

	@Column(name = "num", nullable = false)
	public Integer getNum() {
		return this.num;
	}

	public void setNum(Integer num) {
		this.num = num;
	}
	@Column(name = "score", nullable = false, insertable=false)
	public Integer getScore() {
		return this.score;
	}

	public void setScore(Integer score) {
		this.score = score;
	}
	
	@Transient
	public String getTotal(){
		DecimalFormat df = new DecimalFormat("#.00");
		return df.format(num*product.getTruePrice())+"";
	}
    @Column(name="flag",insertable=false,nullable=false)
	public Integer getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

}